const data = [
    { id: 1, name: 'Root', parentId: null },
    { id: 2, name: 'Child 1', parentId: 1 },
    { id: 3, name: 'Child 2', parentId: 1 },
    { id: 4, name: 'Grandchild 1', parentId: 2 },
    { id: 5, name: 'Grandchild 2', parentId: 2 },
  ]

const maps = new Map();

for (let item of data) {
    maps.set(item.id,item)
}
let arr = []
for (let item of data) {
    let root = maps.get(item.parentId)
    if(!root) {
        arr.push(item) 
    } else {
       if(root.id==item.parentId) {
           root.children = root.children || []
           root.children.push(item)

       }
    }
   
}

console.log(JSON.stringify(arr, null, 2));



  function arrayToTree(data, parentId = null) {
    let result = [];
    for (let item of data) {
        if (item.parentId === parentId) {
            // 递归构建子树
            const children = arrayToTree(data, item.id);
            if (children.length) {
                item.children = children;
            }
            // 将当前节点添加到结果数组中
            result.push(item);
        }
    }
    return result;
}

// 调用函数并输出结果
// const tree = arrayToTree(data);
// console.log(JSON.stringify(tree, null, 2));
